package com.example.timeemail.fragment

import android.app.Fragment
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.timeemail.R
import com.stone.persistent.recyclerview.adapter.MainListAdapter
import kotlinx.android.synthetic.main.fragment_message.*

/**
 * User:Shine
 * Date:2015-10-20
 * Description:
 */
class MessageFragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View? {
        val inflate = inflater.inflate(R.layout.fragment_message, container, false)
        return inflate
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        // 1. 初始化handler
        initHandler()

        // 2. 列表RecyclerView
        initAdapter()
        main_recycler_view.layoutManager = LinearLayoutManager(activity)
        main_recycler_view.adapter = listAdapter


        // 4. 下拉刷新处理
        main_refresh_layout.setOnRefreshListener {
            uiHandler?.sendEmptyMessageDelayed(MSG_TYPE_REFRESH_FINISHED, 500L)
        }

    }


    private var listAdapter: MainListAdapter? = null
    private var uiHandler: Handler? = null

    companion object {
        private const val MSG_TYPE_REFRESH_FINISHED = 0
        private const val MSG_TYPE_TABS_LOADED = 1
    }


    private fun initHandler() {
        uiHandler = Handler {
            when {
                it.what == MSG_TYPE_REFRESH_FINISHED -> main_refresh_layout.finishRefresh()
                it.what == MSG_TYPE_TABS_LOADED -> listAdapter?.onTabsLoaded()
            }
            false
        }
    }

    /**
     * 初始化Adapter
     */
    private fun initAdapter() {
        listAdapter = MainListAdapter(activity as AppCompatActivity)
        listAdapter!!.setLoadingTabsListener {
            // 800ms后，加载tabs成功
            uiHandler?.sendEmptyMessageDelayed(MSG_TYPE_TABS_LOADED, 800L)
        }
    }
}